package com.myrobot.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

	public static byte[] readFileByte(File file) {
		byte[] bs = null;
		if (file.exists() && file.isFile()) {
			ByteArrayOutputStream ba = null;
			InputStream in = null;
			try {
				ba = new ByteArrayOutputStream();
				in = new FileInputStream(file);
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = in.read(buf)) != -1) {
					ba.write(buf, 0, len);
				}
				bs = ba.toByteArray();
			} catch (IOException e) {
			} finally {

				try {
					if (in != null) {
						in.close();
						in = null;
					}
					if (ba != null) {
						ba.close();
						ba = null;
					}
				} catch (IOException e1) {
				}
			}
		}
		return bs;
	}

	public static void writeFileByte(File file, byte[] data) {
		if (file != null && file.getParentFile() != null && !file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(data);
		} catch (IOException e) {
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e1) {
			}
		}
	}

	public static String readFile(File file) {
		String data = "";
		if (file.exists() && file.isFile()) {
			ByteArrayOutputStream bs = null;
			InputStream in = null;
			try {
				bs = new ByteArrayOutputStream();
				in = new FileInputStream(file);
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = in.read(buf)) != -1) {
					bs.write(buf, 0, len);
				}
				data = bs.toString();
			} catch (IOException e) {
			} finally {

				try {
					if (in != null) {
						in.close();
						in = null;
					}
					if (bs != null) {
						bs.close();
						bs = null;
					}
				} catch (IOException e1) {
				}
			}
		}
		return data;
	}

	public static void writeFile(File file, String data) {
		if (file != null && file.getParentFile() != null && !file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		OutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(data.getBytes());
		} catch (IOException e) {
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e1) {
			}
		}
	}

	public static String readFile(String fileName) {
		if (fileName != null) {
			return readFile(new File(fileName));
		}
		return null;
	}

	public static void writeFile(String fileName, String data) {
		if (fileName != null && data != null) {
			writeFile(new File(fileName), data);
		}
	}

}
